/**
 * 收到请求时，把网页响应回去
 * 请求：http://localhost:8081/
 * 将index.html响应到前端
 */
const http=require('http');
const url=require('url');
const fs=require('fs');
const path=require('path');
const https=require('https');
const cheerio=require('cheerio');

var reqUrl='https://maoyan.com/films';
var movieList=[];

//! req请求所带有的信息   res响应时给客户端的东西
http.createServer((req,res)=>{
    var urlObj=url.parse(req.url);
    // console.log(urlObj);
    var pathname=urlObj.pathname;
    if(pathname=='/'){
        //!写入页面
        var filePath=path.join(__dirname,'/index.html');
        fs.readFile(filePath,(err,data)=>{
            if(err){
                console.log(err);
            }else{
                //! 加上写入头 
                res.writeHead(200,{'Content-Type':"text/html;charset=utf8"});
                res.write(data);
                res.end()
            }
        })
    }else if(pathname=='/getlist'){
        //!爬程序，爬数据过程
        https.get(reqUrl,(resObj)=>{
            var htmlStr="";
            resObj.on('data',(chunk)=>{
                htmlStr+=chunk;//!chunk buffere类型拼接字符串自动转为utf8
            })
            resObj.on('end',()=>{
                console.log(htmlStr);//!打印出来html代码
                var $=cheerio.load(htmlStr);
                $(".movie-item-title a").each((i,el)=>{
                    // console.log($(el).text());

                    var movieName=$(el).text();
                    // console.log(JSON.parse($(el).attr('data-val')).movieId);

                    var movieId=$(el).attr('data-val');
                    movieId=movieId.slice(movieId.indexOf(':')+1,-1);
                    // console.log(movieId);

                    var num1=$(el).parent().next().children(".integer").text();
                    var num2=$(el).parent().next().children(".fraction").text();
                    var movieRate=num1+num2;

                    var movieObj={movieId:movieId,movieName:movieName,movieRate:movieRate};
                    movieList.push(movieObj);
                })
                res.writeHead(200,{"Content-Type":"text/plain"});
                res.write(JSON.stringify(movieList));
                res.end();
            })
        })

    }
}).listen(8081);